//导入
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


// const multer = require('multer');
// const cors = require('cors');
// app.use(cors());
// // 设置存储配置
// const storage = multer.diskStorage({
//   destination: function (req, file, cb) {
//     cb(null, 'uploads/') // 设置上传文件保存的目录，不存在会自动创建
//   },
//   filename: function (req, file, cb) {
//     cb(null, Date.now() + path.extname(file.originalname)) // 更改文件名为时间戳加扩展名
//   }
// });
// const upload = multer({ storage: storage });
// // 创建 uploads 文件夹
// const fs = require('fs');
// const dir = './uploads';
// if (!fs.existsSync(dir)) {
//   fs.mkdirSync(dir);
// }
// app.post('/upload', upload.single('file'), (req, res) => {
//   if (!req.file) {
//     return res.status(400).send('No file uploaded.');
//   }
//   console.log(req.file, req.body)
//   // 文件已成功上传
//   res.json({
//     message: 'File uploaded successfully',
//     fileName: req.file.filename,
//     filePath: `/uploads/${req.file.filename}`
//   });
// });


app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); // 静态文件夹

//路由
var images = require('./routes/images');
var users = require('./routes/users');
var updata = require('./routes/updata.js')
var course = require('./routes/course.js')
var admin = require('./routes/admin.js')
app.use('/images', images);
app.use('/users', users);
app.use('/updata', updata)
app.use('/course', course)
app.use('/admin', admin)

const cors = require("cors");
app.use(cors());

app.all('*', (req, res) => {
  res.status(404)
  res.send(`<h1>404 Not Found</h1>`)
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;